/**
 * Created by huotaol on 2017/5/4.
 */
import {call, fork, put, take, takeLatest} from "redux-saga/effects";
import {request} from "../../../common/util/RequestUtil";
import * as types from "../../constant/ActionType";
import * as Url from "../../constant/Url";
import * as BuyCarAction from "../action/BuyCar";

const HOT_BRAND_ARRAY = [];
HOT_BRAND_ARRAY.push('奔驰');
HOT_BRAND_ARRAY.push("本田");
HOT_BRAND_ARRAY.push("丰田");
HOT_BRAND_ARRAY.push("奥迪");
HOT_BRAND_ARRAY.push("标致");
HOT_BRAND_ARRAY.push("宝马");
const HOT_BRAND = {'热门品牌': HOT_BRAND_ARRAY};

function* fetchBrand() {
    let data = {...HOT_BRAND};
    try {
        const url = Url.BASE_URL + '/car/comm/get_all_car_brand';
        const json = yield call(request, url);
        data = Object.assign({}, data, json.data);
    } catch (err) {

    } finally {
        yield put(BuyCarAction.receiveBrand(data));
    }
}

const SERIES = ['不限车系'];

function* fetchSeries(brand) {
    let data = [...SERIES];
    try {
        const url = Url.BASE_URL + '/car/comm/get_car_set_by_brand';
        const param = new FormData();
        param.append('val', brand);
        console.log('fetSeries before');
        const json = yield call(request, url, 'post', param);
        data = data.concat(json.data);
    } catch (e) {
        setTimeout(fetchSeries, 5000, brand);
    } finally {
        console.log('fetchSeries finally');
        yield put(BuyCarAction.receiveSeries(data));
    }
}

function* watchFetchSeries() {
    while (true) {
        const {brand} = yield take(types.SERIES_REQUEST);
        yield fork(fetchSeries, brand);
    }
}

export default [takeLatest(types.BRAND_FETCH, fetchBrand), fork(watchFetchSeries),];